package com.sk.wordandpdf;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class WordUtil {
    /**
     * @param filePath 文件路径
     * @Title: getTextFromWord
     * @Description: 读取word
     * @return: String 读出的Word的内容
     */
    public static String getTextFromWord(String filePath) {

        String result = null;
        File file = new File(filePath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            String fileName = file.getName();
            String hz = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            //声明相关的工作薄对象
            if(hz.equals(".doc")) {
                @SuppressWarnings("resource")
                WordExtractor wordExtractor = new WordExtractor(fis);
                result = wordExtractor.getText();
            }else{
                XWPFDocument xdoc = new XWPFDocument(fis);
                XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                result = extractor.getText();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
